import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
import routes from "./routes";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes,
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
});

const whitePath = [
  "Home",
  "Search",
  "Detail",
  "Login",
  "addCartSuccess",
  "Register",
];

router.beforeEach(async (to, from, next) => {
  // console.log(1);

  const token = store.state.user.token;
  if (token) {
    // console.log(2);
    if (to.name === "Login") {
      next("/home");
    } else {
      const isUserInfo = !!store.state.user.userInfo.nickName;

      if (isUserInfo) {
        next();
      } else {
        try {
          await store.dispatch("user/getUserInfo");
          next();
        } catch (err) {
          store.dispatch("user/resetToken");
          next("/login");
        }
      }
    }
  } else {
    if (whitePath.includes(to.name)) {
      console.log(3);
      next();
    } else {
      console.log(4);
      next("/login");
    }
  }
});

export default router;
